<template>
  <view class="page">
    <!-- 页头导航 -->
    <view class="header-nav">
      <view class="nav-left" @tap="goBack">
        <image
          class="back-icon"
          src="/static/icons/left_arrow.png"
          mode="aspectFit"
        ></image>
      </view>
      <view class="nav-title">编辑工作时间</view>
      <view class="nav-right">
        <text class="save-btn" @tap="handleSubmit" :class="{ disabled: !canSubmit }">保存</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="container">
      <!-- 工作时间选择 -->
      <view class="form-item">
        <view class="form-label">工作时间</view>
        <view class="time-picker-section">
          <picker
            mode="time"
            :value="formData.workStartTime"
            @change="onWorkStartTimeChange"
          >
            <view class="time-picker">
              <text class="time-label">上班时间</text>
              <text class="time-value">{{ formData.workStartTime || '请选择' }}</text>
            </view>
          </picker>
          <text class="time-separator">至</text>
          <picker
            mode="time"
            :value="formData.workEndTime"
            @change="onWorkEndTimeChange"
          >
            <view class="time-picker">
              <text class="time-label">下班时间</text>
              <text class="time-value">{{ formData.workEndTime || '请选择' }}</text>
            </view>
          </picker>
        </view>
      </view>

      <!-- 加班情况选择 -->
      <view class="form-item">
        <view class="form-label">加班情况</view>
        <view v-if="overtimeList.length === 0" class="loading-placeholder">
          <text class="loading-text">加载中...</text>
        </view>
        <view v-else class="tag-selection">
          <view
            v-for="item in overtimeList"
            :key="item.id"
            class="tag-item"
            :class="{ selected: formData.overtimeSituation === item.dataKey }"
            @tap="selectOvertime(item)"
          >
            <image v-if="item.icon" :src="item.icon" class="tag-icon" mode="aspectFit"></image>
            <text class="tag-text">{{ item.value }}</text>
          </view>
        </view>
      </view>

      <!-- 休息时间选择 -->
      <view class="form-item">
        <view class="form-label">休息时间</view>
        <view v-if="restTimeList.length === 0" class="loading-placeholder">
          <text class="loading-text">加载中...</text>
        </view>
        <view v-else class="tag-selection">
          <view
            v-for="item in restTimeList"
            :key="item.id"
            class="tag-item"
            :class="{ selected: formData.restTime === item.dataKey }"
            @tap="selectRestTime(item)"
          >
            <image v-if="item.icon" :src="item.icon" class="tag-icon" mode="aspectFit"></image>
            <text class="tag-text">{{ item.value }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { modifyCompanyInfoApi, getDictionaryDataListByTypesApi } from "@/api/company.js";

// 页面参数
const companyId = ref('');

// 表单数据
const formData = ref({
  workStartTime: '',
  workEndTime: '',
  overtimeSituation: '',
  restTime: ''
});

// 加班情况数据
const overtimeList = ref([]);

// 休息时间数据
const restTimeList = ref([]);

// 页面加载时获取参数
onMounted(async () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options.companyId) {
    companyId.value = options.companyId;
  }
  
  if (options.workStartTime) {
    formData.value.workStartTime = options.workStartTime;
  }
  if (options.workEndTime) {
    formData.value.workEndTime = options.workEndTime;
  }
  if (options.overtimeSituation) {
    formData.value.overtimeSituation = options.overtimeSituation;
  }
  if (options.restTime) {
    formData.value.restTime = options.restTime;
  }
  
  try {
    // 加载基础数据
    await Promise.all([
      loadOvertimeData(),
      loadRestTimeData()
    ]);
  } catch (error) {
    console.error('页面数据加载失败:', error);
  }
});

// 是否可以提交
const canSubmit = computed(() => {
  return true; // 工作时间相关字段都不是必填的
});

// 加载加班情况数据
const loadOvertimeData = async () => {
  try {
    const data = await getDictionaryDataListByTypesApi(['overtime_situation']);
    if (data && data.overtime_situation) {
      overtimeList.value = (data.overtime_situation || []).sort(
        (a, b) => (a.sort || 0) - (b.sort || 0)
      );
    } else {
      console.warn('加班情况数据为空或格式不正确');
      overtimeList.value = [];
    }
  } catch (error) {
    console.error('加载加班情况数据失败:', error);
    overtimeList.value = [];
  }
};

// 加载休息时间数据
const loadRestTimeData = async () => {
  try {
    const data = await getDictionaryDataListByTypesApi(['rest_time']);
    if (data && data.rest_time) {
      restTimeList.value = (data.rest_time || []).sort(
        (a, b) => (a.sort || 0) - (b.sort || 0)
      );
    } else {
      console.warn('休息时间数据为空或格式不正确');
      restTimeList.value = [];
    }
  } catch (error) {
    console.error('加载休息时间数据失败:', error);
    restTimeList.value = [];
  }
};

// 工作时间选择
const onWorkStartTimeChange = (e) => {
  const startTime = e.detail.value;
  formData.value.workStartTime = startTime;
  
  // 如果下班时间已选择且早于上班时间，给出提示
  if (formData.value.workEndTime && startTime >= formData.value.workEndTime) {
    uni.showToast({
      title: '上班时间不能晚于或等于下班时间',
      icon: 'none'
    });
  }
};

const onWorkEndTimeChange = (e) => {
  const endTime = e.detail.value;
  formData.value.workEndTime = endTime;
  
  // 如果上班时间已选择且下班时间早于上班时间，给出提示
  if (formData.value.workStartTime && endTime <= formData.value.workStartTime) {
    uni.showToast({
      title: '下班时间不能早于或等于上班时间',
      icon: 'none'
    });
  }
};

// 加班情况选择
const selectOvertime = (item) => {
  formData.value.overtimeSituation = item.dataKey;
};

// 休息时间选择
const selectRestTime = (item) => {
  formData.value.restTime = item.dataKey;
};

// 提交表单
const handleSubmit = async () => {
  if (!canSubmit.value) return;

  try {
    uni.showLoading({
      title: "保存中...",
      mask: true,
    });

    // 构建workTime字段 - 包含时间 + dataKey
    const workTimeParts = [];
    if (formData.value.workStartTime && formData.value.workEndTime) {
      workTimeParts.push(`${formData.value.workStartTime}-${formData.value.workEndTime}`);
    }
    if (formData.value.overtimeSituation) {
      workTimeParts.push(formData.value.overtimeSituation);
    }
    if (formData.value.restTime) {
      workTimeParts.push(formData.value.restTime);
    }
    
    const workTime = workTimeParts.length > 0 ? workTimeParts.join(' ') : '';

    const submitData = {
      companyId: companyId.value,
      workTime: workTime
    };

    await modifyCompanyInfoApi(submitData);

    uni.hideLoading();
    uni.showToast({
      title: "保存成功",
      icon: "success",
      duration: 2000
    });

    // 延迟跳转，让用户看到成功提示
    setTimeout(() => {
      // 发送事件通知编辑页面重新获取数据
      uni.$emit('companyInfoUpdated');
      uni.navigateBack();
    }, 2000);

  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || "保存失败",
      icon: "none",
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  width: 120rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-btn {
  font-size: 32rpx;
  color: #007aff;
  font-weight: 500;
  padding: 10rpx 20rpx;
  border-radius: 6rpx;
  background-color: rgba(0, 122, 255, 0.1);
  transition: all 0.3s ease;
}

.save-btn:active {
  background-color: rgba(0, 122, 255, 0.2);
}

.save-btn.disabled {
  color: #c0c0c0;
  background-color: rgba(192, 192, 192, 0.1);
}

.container {
  padding: 20rpx;
}

.form-item {
  display: flex;
  flex-direction: column;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: #fff;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
}

.form-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.form-label {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
}

/* 工作时间选择器样式 */
.time-picker-section {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx 0;
}

.time-picker {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 10rpx 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
}

.time-label {
  font-size: 28rpx;
  color: #666;
}

.time-value {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.time-separator {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

/* 标签选择样式 */
.tag-selection {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  padding: 20rpx 0;
  width: 100%;
  box-sizing: border-box;
}

.tag-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  background-color: #f8f9fa;
  border-radius: 25rpx;
  border: 2rpx solid #e9ecef;
  transition: all 0.3s ease;
  cursor: pointer;
  min-width: 120rpx;
  box-sizing: border-box;
}

.tag-item:hover {
  background-color: #e9ecef;
  transform: translateY(-2rpx);
}

.tag-item.selected {
  background-color: #e6f7ff;
  border-color: #007aff;
  color: #007aff;
  box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.2);
}

.tag-icon {
  width: 32rpx;
  height: 32rpx;
  flex-shrink: 0;
}

.tag-text {
  font-size: 28rpx;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.tag-item.selected .tag-text {
  color: #007aff;
  font-weight: 500;
}

/* 加载状态和错误处理样式 */
.loading-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 120rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  border: 2rpx dashed #ddd;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}
</style>
